/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-05-27 08:54:20
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-06-04 11:03:03
 * @FilePath: /vue3-uniapp/src/utils/index.ts
 */
export const getStaticImage = (path: string) => {
    return import.meta.env.VITE_STATIC_URL + path;
};

export const debounceFn = <T extends (...args: any[]) => any>(
    fn: T,
    wait: number,
    immediate = false
): [(...args: Parameters<T>) => void, () => void] => {
    let timer: unknown;

    let lastArgs: Parameters<T> | undefined;
    const excute = (...args: Parameters<T>) => {
        lastArgs = args;

        if (timer) {
            clearTimeout(timer as number | string | undefined);
        }

        if (immediate && !timer) {
            fn(...args);
        }

        timer = setTimeout(() => {
            if (!immediate) {
                fn(...(lastArgs as Parameters<T>));
            }
            timer = undefined;
        }, wait);
    };

    const clear = () => {
        if (timer) {
            clearTimeout(timer as number | string | undefined);
            timer = null;
        }
    };

    return [excute, clear];
};

export const throttleFn = <T extends (...args: any[]) => any>(
    fn: T,
    limit: number
): [(...args: Parameters<T>) => void, () => void] => {
    let timer: unknown;
    let lastArgs: Parameters<T> | undefined;

    const excute = (...args: Parameters<T>) => {
        lastArgs = args;

        if (!timer) {
            timer = setTimeout(() => {
                fn(...(lastArgs as Parameters<T>));
                timer = null;
            }, limit);
        }
    };

    const clear = () => {
        if (timer) {
            clearTimeout(timer as string | number | undefined);
            timer = null;
        }
    };

    return [excute, clear];
};

export * from './array';
